package com.ergwang.dao;

import com.ergwang.Model.Admin;
import com.ergwang.Model.User;
import com.ergwang.Model.admin.bo.AdminChangePwdBO;
import com.ergwang.utils.DruidUtils;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Creat by ergWang
 * Date: 2020/5/29
 * Time: 00:25
 */
public class AdminDaoImpl implements AdminDao {

    /**
     * 查询数据，登陆！
     *
     * @param admin
     * @return
     */
    public Admin login(Admin admin) {
        // 数据库查询
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        Admin query = null;
        try {
            query = runner.query("select * from admin where email = ? and pwd = ?",
                    new BeanHandler<Admin>(Admin.class),
                    admin.getEmail(),
                    admin.getPwd());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;
    }

    public List<Admin> allAdmins() {
        // 查询数据库数据
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        List<Admin> query = null;
        try {
            query = queryRunner.query("select * from admin", new BeanListHandler<Admin>(Admin.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;
    }

    /**
     * 1. 当账号搜索栏有数据：select * from admin where email like ?
     * 2. 昵称栏有数据：select * from admin where nickname like ?
     * 3. 两栏都有数据：select * from admin where nickname like ? and like ?
     * 4. 两栏都没有数据： 调用allAdmins()
     * <p>
     * // 如果查询条件多，则特别复杂  ==》 使用动态sql思想：
     *
     * @param admin
     * @return
     */
    public List<Admin> getSearchAdmins(Admin admin) {
        Map<String, Object> sqlMap = getDynamicSql(admin);
        String sql = (String) sqlMap.get("sql");
        List<String> params = (List<String>) sqlMap.get("params");
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<Admin> admins = null;
        try {
            admins = runner.query(sql, new BeanListHandler<Admin>(Admin.class), params.toArray());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return admins;
    }

    /**
     * 动态sql的思想
     * 非常重要！！！！！
     *
     * @param admin
     * @return
     */
    private Map<String, Object> getDynamicSql(Admin admin) {
        String base = "select * from admin where 1 = 1 ";
        List<String> params = new ArrayList<String>();


        System.out.println(admin);


        if (!StringUtils.isNullOrEmpty(admin.getEmail())) {
            base = base + " and email like ?";
            params.add("%" + admin.getEmail() + "%");
        }
        if (!StringUtils.isNullOrEmpty(admin.getNickname())) {
            base = base + " and nickname like ?";
            params.add("%" + admin.getNickname() + "%");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sql", base);
        map.put("params", params);
        return map;
    }

    /**
     * 添加管理员账户
     * @param admin
     * @return
     */
    public int addAdminss(Admin admin) {
        // 添加到数据库
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int rows = 0;
        try {
            rows = runner.update("insert into admin (email, nickname, pwd) values (?,?,?)",
                    admin.getEmail(),
                    admin.getNickname(),
                    admin.getPwd());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows;
    }

    /**
     * 根据id删除选中的管理员账户
     * @param admin
     * @return
     */
    public int deleteAdmins(Admin admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int rows = 0;
        try {
            rows = runner.update("delete from admin where id=?",
                    admin.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rows;
    }

    /**
     * 根据id获取选中的管理员账户的详细信息
     * @param admin
     * @return
     */
    public Admin getAdminsInfo(Admin admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        Admin query = null;
        try {
            query = runner.query("select * from admin where id = ?",
                    new BeanHandler<Admin>(Admin.class),
                    admin.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;
    }

    /**
     * 根据admin的id查询数据库的账户信息，将其改为admin的数据
     * @param admin
     * @return
     */
    public int updateAdminss(Admin admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int update = 0;
        try {
            update = runner.update("update admin set email=?,nickname=?,pwd=? where id =?",
                    admin.getEmail(),
                    admin.getNickname(),
                    admin.getPwd(),
                    admin.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;
    }

    /**
     * 修改密码
     * 成功返回1，旧密码错返回404，两次不一致500
     * @param changePwdBO
     * @return
     */
    public int changePwd(AdminChangePwdBO changePwdBO) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int update = 0;
        try {
            update = runner.update("update admin set pwd = ? where nickname = ?",
                    changePwdBO.getNewPwd(), changePwdBO.getAdminToken());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;
    }

    //获取旧密码
    public String getOldPwd(String adminToken) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        String oldPwd = null;
        try {
            User user = runner.query("select pwd from admin where nickname = ?",
                      new BeanHandler<User>(User.class),
                      adminToken);
            oldPwd = user.getPwd();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return oldPwd;
    }
}
